import Vue from 'vue'
import Router from 'vue-router'
import { getCookie } from '@/untils/storage'
import store from '../store'

const Home = r => require(['@/views/Home/index.vue'], r)
const Brand = r => require(['@/views/Brand/index.vue'], r)
const Purchase = r => require(['@/views/Home/purchase.vue'], r)
const Assortment = r => require(['@/views/Assortment/index.vue'], r)
const Shopcart = r => require(['@/views/Shopcart/index.vue'], r)
const Login = r => require(['@/views/Login/login.vue'], r)
const test = r => require(['@/views/test.vue'], r)

Vue.use(Router)
const myRouter = new Router({
  linkActiveClass: 'router-active',
  routes: [
    {
      path: '/',
      redirect: '/index'
    },
    {
      path: '/index',
      component: Home,
      name: 'Index'
    },
    {
      path: '/brand',
      name: 'Brand',
      component: Brand
    },
    {
      path: '/assortment',
      name: 'Assortment',
      component: Assortment
    },
    {
      path: '/purchase',
      component: Purchase,
      name: 'Purchase'
    },
    {
      path: '/shopcart',
      component: Shopcart,
      name: 'Shopcart'
    },
    {
      path: '/login',
      component: Login,
      name: 'Login'
    },
    {
      path: '/test',
      component: test,
      name: 'Test'
    }
  ]
})

myRouter.beforeEach((to, from, next) => {
  // 切换路由 存在Token值 就去更新用户信息
  if (getCookie('Token')) {
    store.dispatch('getUserData')
  }
  if (to.matched.some(record => record.meta.requireAuth)) {
    // if not, redirect to login page.
    if (!getCookie('Token')) {
      next({
        path: '/login',
        query: { redirect: to.fullPath }
      })
    } else {
      next()
    }
  } else {
    next()
  }
})

export default myRouter
